package com.hwy.filter;

/*
* 检查用户是否已经完成登录的过滤器
* */

import com.alibaba.fastjson.JSON;
import com.hwy.common.BaseContext;
import com.hwy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        log.info("拦截到请求：{}",request.getRequestURI());

        //哪些请求不用拦截
        String[] url = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",//移动端登录
                "/user/sendMsg",//移动端发送短信验证码
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断是否为url[]中的请求
        boolean check = check(url, request.getRequestURI());
        if(check == true){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //判断是否为登录状态，如果已经登录就放行
        if(request.getSession().getAttribute("employee") != null){

            //将用户id存进本地线程
            BaseContext.setThreadLocal((Long) request.getSession().getAttribute("employee"));

            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //判断是否为登录状态，如果已经登录就放行---移动端
        if(request.getSession().getAttribute("user") != null){

            //将用户id存进本地线程
            BaseContext.setThreadLocal((Long) request.getSession().getAttribute("user"));

            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //如果未登录就返回未登录状态，通过输出流方式向客户端页面响应数据
        response.getWriter().write((JSON.toJSONString((R.error("NOTLOGIN")))));
        return;

    }


    //判断将要拦截的请求是否为url[]里的
    public boolean check(String[] url,String requestUrI){
        for (String s : url) {
            boolean match = PATH_MATCHER.match(s, requestUrI);
            if (match == true){
                return true;
            }
        }
        return false;
    }
}
